package com.xyc.petmallsystem.controller;

import com.xyc.petmallsystem.pojo.Personal;
import com.xyc.petmallsystem.pojo.User;
import com.xyc.petmallsystem.repository.PersonalRepository;
import com.xyc.petmallsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Joel
 * @date 2021/12/5
 */

@RestController
@RequestMapping("/personal")
public class PersonalController {

    @Autowired
    PersonalRepository personalRepository;

    @Autowired
    UserRepository userRepository;

    /*
    查找所有
     */
    @GetMapping("/find")
    public List<Personal> find() {
        return personalRepository.findAll();
    }

    /*
    根据id查找
     */
    @GetMapping("/findById/{id}")
    public Personal findById(@PathVariable("id") Integer id) {
        return personalRepository.findById(id).get();
    }

    /*
    更新
     */
    @PostMapping("/save")
    public String save(@RequestBody Personal personal) {  // 接收修改数据后的表单
        Personal personal2 = personalRepository.save(personal);
        if (personal2 != null)
            return "success";
        return "error";
    }

    /*
    根据id  清空昵称，电话，地址
     */
    @GetMapping("/clearById/{id}")
    public void clearById(@PathVariable("id") Integer id) {
        Personal personal = personalRepository.findById(id).get();
        personal.setNickname("");
        personal.setPhone("");
        personal.setAddress("");
        personal.setPost(100000);
        personal.setReceive("");
        personalRepository.save(personal);
    }


    /*
    分页
     */
    @GetMapping("/findPage/{page}/{size}")
    public Page<Personal> findPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest pageable = PageRequest.of(page - 1, size);
        return personalRepository.findAll(pageable);
    }

    /*
    根据用户名来查找
     */
    @GetMapping("/findByName/{name}")
    public Personal findByName(@PathVariable String name) {
        User user = userRepository.findByName(name);
        Integer user_id = user.getId();
        return personalRepository.getInfo(user_id);
    }

    /*
    删除个人中心
     */
    @GetMapping("/delById/{id}")
    public void delById(@PathVariable Integer id) {
        personalRepository.deleteById(id);
    }
}
